<template>
  <div class="app-iframe-container">
    <el-row>
      <el-col :span="15">
        <el-row >
          <el-col :span="24">
            <!--<el-button v-permission="['0010101']" type="primary" >优化</el-button>-->
            <el-button :disabled="!buttonExecuteValid" type="primary" @click="executeSql">执行</el-button>
            <el-button type="primary" @click="beautifySql">美化</el-button>
            <el-button type="primary" @click="analysisSql">分析</el-button>
            <el-button :disabled="!buttonCollectValid" type="primary" @click="collectSql">收藏</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-select v-model="selectedDatabase" filterable placeholder="请选择要查询的数据库" @change="databaseChange">
              <el-option v-for="item in databases" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <ace-editor ref="ace" :custom-complete-data="customCompleteData"/>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="9">
        <el-row>
          <el-col :span="24">
            <el-tabs v-model="activeTab" type="card" @tab-click="handleClick">
              <el-tab-pane label="表-字段" name="table">
                <el-row>
                  <el-col :span="24">
                    <el-select v-model="selectedTable" filterable placeholder="请选择表" @change="tableChange">
                      <el-option v-for="item in tables" :key="item.tableName" :value="item.tableName" :label="item.tableName"/>
                    </el-select>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-table
                      :data="tableColumns"
                      fit
                      border
                      highlight-current-row
                      height="400px"
                      style="width: 100%;"
                      @row-dblclick="columnSelect">
                      <el-table-column width="100px" show-tooltip-when-overflow label="字段" prop="field"/>
                      <el-table-column width="100px" show-tooltip-when-overflow label="类型" prop="type"/>
                      <el-table-column width="300px" show-tooltip-when-overflow label="备注" prop="remark"/>
                      <el-table-column width="50px" show-tooltip-when-overflow label="允许NULL" prop="nullAble"/>
                      <el-table-column width="100px" show-tooltip-when-overflow label="默认值" prop="defaultValue"/>
                    </el-table>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="收藏" name="collect">
                <el-row>
                  <el-col :span="24">
                    <el-input placeholder="搜索名称"/>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-table
                      :data="collectSqls"
                      fit
                      highlight-current-row
                      height="400px"
                      style="width: 100%;">
                      <el-table-column label="名称" prop="name"/>
                      <el-table-column label="时间" >
                        <template slot-scope="scope">
                          {{ scope.row.addDate | parseDate }}
                        </template>
                      </el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="scope">
                          <el-tooltip class="item" effect="dark" content="使用" placement="top-start">
                            <el-button icon="el-icon-check" circle @click="applyCollectSql(scope.row.sql)"/>
                          </el-tooltip>
                          <el-tooltip class="item" effect="dark" content="替换" placement="top-start">
                            <el-button icon="el-icon-refresh" circle @click="editCollectSql(scope.row.sql)"/>
                          </el-tooltip>
                          <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                            <el-button icon="el-icon-delete" circle @click="deleteCollectSql(scope.row.id)"/>
                          </el-tooltip>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row v-show="queryResult.useTime !== -1">
      耗时:{{ queryResult.useTime }} ms, 总共 {{ queryResult.data.length }} 条记录
    </el-row>
    <el-row>
      <el-table
        :data="queryResult.data"
        border
        highlight-current-row>
        <el-table-column v-for="item in queryResult.columnNames" :key="item" :label="item" :prop="item" :show-tooltip-when-overflow="true" width="200px"/>
      </el-table>
    </el-row>
  </div>
</template>

<script>
import AceEditor from '@/components/AceEditor'
import databaseApi from '@/api/dbms/database'
import databaseQueryApi from '@/api/dbms/databaseQuery'
import userSqlCollectApi from '@/api/dbms/userSqlCollect'
import sqlFormatter from 'sql-formatter'

export default {
  name: 'DbmsDatabaseQuery',
  components: {
    AceEditor: AceEditor
  },
  data() {
    return {
      activeTab: 'table',
      tables: [],
      tableColumns: [],
      databases: [],
      selectedDatabase: '',
      selectedTable: '',
      collectSqls: [
      ],
      queryResult: {
        useTime: -1,
        data: [],
        columnNames: []
      }
    }
  },
  computed: {
    /** *
       * 执行按钮是否可用
       */
    buttonExecuteValid() {
      if (this.selectedDatabase !== undefined && this.selectedDatabase !== null && this.selectedDatabase !== '') {
        return true
      }
      return false
    },
    /** *
       *  收藏按钮是否可用
       */
    buttonCollectValid() {
      if (this.selectedDatabase !== undefined && this.selectedDatabase !== null && this.selectedDatabase !== '') {
        return true
      }
      return false
    },
    customCompleteData() {
      var data = []
      for (var i = 0; i < this.tables.length; i++) {
        var table = this.tables[i]
        data.push({ meta: '表', caption: table.tableName, value: table.tableName, score: 500 })
        for (var j = 0; j < table.fields.length; j++) {
          var field = table.fields[j]
          data.push({ meta: '字段', caption: field.field, value: field.field, score: 400 })
        }
      }
      return data
    }
  },
  mounted() {
    this.getDatabaseList()
  },
  methods: {
    getDatabaseList() {
      databaseApi.list().then(response => {
        if (response.data.code === 200) {
          var responseData = response.data.data
          this.databases = responseData.records
        } else {
          this.$message.error(response.data.msg)
        }
      }
      )
    },
    getSqlCollectSqlList(databaseId) {
      userSqlCollectApi.list({ databaseId }).then(response => {
        if (response.data.code === 200) {
          var responseData = response.data.data
          this.collectSqls = responseData.records
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    getTables(databaseId) {
      databaseQueryApi.tables({ databaseId }).then(response => {
        if (response.data.code === 200) {
          var responseData = response.data.data
          this.tables = responseData
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    databaseChange(databaseId) {
      this.getTables(databaseId)
      this.getSqlCollectSqlList(databaseId)
    },
    tableChange(tableName) {
      for (var i = 0; i < this.tables.length; i++) {
        if (this.tables[i].tableName === tableName) {
          this.tableColumns = this.tables[i].fields
        }
      }
    },
    columnSelect(row, column, event) {
      const field = row.field
      this.$refs.ace.$ace.setValue(this.$refs.ace.$ace.getValue() + ' ' + field)
    },
    /** *
       * 执行sql
       */
    executeSql() {
      if (!this.selectedDatabase) {
        return
      }
      var postData = {}
      postData.databaseId = this.selectedDatabase
      postData.sql = this.$refs.ace.$ace.getValue()
      databaseQueryApi.execute(postData).then(response => {
        if (response.data.code === 200) {
          var responseData = response.data.data
          this.queryResult = responseData
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    // 分析SQL
    analysisSql() {
      if (!this.selectedDatabase) {
        return
      }
      var postData = {}
      postData.databaseId = this.selectedDatabase
      postData.sql = this.$refs.ace.$ace.getValue()
      databaseQueryApi.analysis(postData).then(response => {
        if (response.data.code === 200) {
          var responseData = response.data.data
          this.queryResult = responseData
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    /** *
       * 美化sql
       */
    beautifySql() {
      let sql = this.$refs.ace.$ace.getValue()
      sql = sqlFormatter.format(sql)
      this.$refs.ace.$ace.setValue(sql)
    },
    /** *
       * 收藏sql
       */
    collectSql() {
      if (this.$refs.ace.$ace.getValue().length < 8) {
        this.$message.error('SQL长度至少为8')
        return
      }
      this.$prompt('请输入收藏名称', '收藏', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        var postData = {}
        postData.sql = this.$refs.ace.$ace.getValue()
        postData.databaseId = this.selectedDatabase
        postData.name = value
        userSqlCollectApi.add(postData).then(response => {
          if (response.data.code === 200) {
            this.$message.success('操作成功')
            this.getSqlCollectSqlList(this.selectedDatabase)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    /** *
       * 使用收藏的SQL
       */
    applyCollectSql(sql) {
      this.$refs.ace.$ace.setValue(sql)
    },
    /** *
       * 删除收藏的SQL
       * @param id
       */
    deleteCollectSql(id) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userSqlCollectApi.del({ id }).then(response => {
          if (response.data.code === 200) {
            this.$message.success('操作成功')
            this.getSqlCollectSqlList(this.selectedDatabase)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    editCollectSql(id) {
      if (this.$refs.ace.$ace.getValue().length < 8) {
        this.$message.error('SQL长度至少为8')
        return
      }
      var postData = {}
      postData.id = id
      postData.sql = this.$refs.ace.$ace.getValue()
      userSqlCollectApi.edit(postData).then(response => {
        if (response.data.code === 200) {
          this.$message.success('操作成功')
          this.getSqlCollectSqlList(this.selectedDatabase)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    }
  }
}
</script>

<style scoped>
  .el-row {
    margin-bottom: 20px;
  }
  .danger{
    color:#F56C6C
  }
</style>
